package com.niannian.util;

import java.util.List;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Environment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.provider.Settings;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URL;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.niannian.activity.RegardsActivity;
import com.niannian.db.MyDBUser;
import com.niannian.imgCache.core.BitmapDecoder;
import com.niannian.MyApplication;
import com.niannian.R;

/**
 * @author shengl
 * 
 */

public class Common {

	/* 线上测试环境 */
	/*
	 * 需要修改获取版本信息的参数
	 */
	// public static String ServerUrl = "http://t.niannian.me/";
	// public static String APK_DOWNLOAD_BASE_URL =
	// "http://t.niannian.me/download"; // 包下载地址

	/* 生产环境 需要修改获取版本信息的参数 */
	public static String ServerUrl = "http://api.dondon.im/"; // API请求地址
	// public static String APK_DOWNLOAD_BASE_URL = "http://dondon.im/download";
	// // 包下载地址

	/* 内网测试环境 */
	// public static String ServerUrl = "http://192.168.0.102:8001/";
	// public static String APK_DOWNLOAD_BASE_URL =
	// "http://192.168.0.102:8001/download"; // 包下载地址

	public static String Server_audio = "media/aud/originals/";

	public static String Server_images_small = "media/img/thumbs/";
	public static String Server_images_middle = "media/img/normals/";
	public static String Server_images_big = "media/img/originals/";

	public static String avatar_thumbs = "media/img/avatar/thumbs/";
	public static String avatar_originals = "media/img/avatar/originals/";

	protected static Map<String, String[]> timeZoneIDs = new LinkedHashMap<String, String[]>(32);
	private static Context curNetWorkContext;
	private static Object curNetWorkLock = new Object();
	public static int curDelNum = 0;
	static {
		timeZoneIDs.put("-12", new String[] { "GMT-12:00", "(GMT -12:00) Eniwetok, Kwajalein" });
		timeZoneIDs.put("-11", new String[] { "GMT-11:00", "(GMT -11:00) Midway Island, Samoa" });
		timeZoneIDs.put("-10", new String[] { "GMT-10:00", "(GMT -10:00) Hawaii" });
		timeZoneIDs.put("-9", new String[] { "GMT-09:00", "(GMT -09:00) Alaska" });
		timeZoneIDs.put("-8", new String[] { "GMT-08:00", "(GMT -08:00) Pacific Time (US &amp; Canada), Tijuana" });
		timeZoneIDs.put("-7", new String[] { "GMT-07:00", "(GMT -07:00) Mountain Time (US &amp; Canada), Arizona" });
		timeZoneIDs.put("-6", new String[] { "GMT-06:00", "(GMT -06:00) Central Time (US &amp; Canada), Mexico City" });
		timeZoneIDs.put("-5", new String[] { "GMT-05:00", "(GMT -05:00) Eastern Time (US &amp; Canada), Bogota, Lima, Quito" });
		timeZoneIDs.put("-4", new String[] { "GMT-04:00", "(GMT -04:00) Atlantic Time (Canada), Caracas, La Paz" });
		timeZoneIDs.put("-3.5", new String[] { "GMT-03:30", "(GMT -03:30) Newfoundland" });
		timeZoneIDs.put("-3", new String[] { "GMT-03:00", "(GMT -03:00) Brassila, Buenos Aires, Georgetown, Falkland Is" });
		timeZoneIDs.put("-2", new String[] { "GMT-02:00", "(GMT -02:00) Mid-Atlantic, Ascension Is., St. Helena" });
		timeZoneIDs.put("-1", new String[] { "GMT-01:00", "(GMT -01:00) Azores, Cape Verde Islands" });
		timeZoneIDs.put("0", new String[] { "GMT", "(GMT) Casablanca, Dublin, Edinburgh, London, Lisbon, Monrovia" });
		timeZoneIDs.put("1", new String[] { "GMT+01:00", "(GMT +01:00) Amsterdam, Berlin, Brussels, Madrid, Paris, Rome" });
		timeZoneIDs.put("2", new String[] { "GMT+02:00", "(GMT +02:00) Cairo, Helsinki, Kaliningrad, South Africa" });
		timeZoneIDs.put("3", new String[] { "GMT+03:00", "(GMT +03:00) Baghdad, Riyadh, Moscow, Nairobi" });
		timeZoneIDs.put("3.5", new String[] { "GMT+03:30", "(GMT +03:30) Tehran" });
		timeZoneIDs.put("4", new String[] { "GMT+04:00", "(GMT +04:00) Abu Dhabi, Baku, Muscat, Tbilisi" });
		timeZoneIDs.put("4.5", new String[] { "GMT+04:30", "(GMT +04:30) Kabul" });
		timeZoneIDs.put("5", new String[] { "GMT+05:00", "(GMT +05:00) Ekaterinburg, Islamabad, Karachi, Tashkent" });
		timeZoneIDs.put("5.5", new String[] { "GMT+05:30", "(GMT +05:30) Bombay, Calcutta, Madras, New Delhi" });
		timeZoneIDs.put("5.75", new String[] { "GMT+05:45", "(GMT +05:45) Katmandu" });
		timeZoneIDs.put("6", new String[] { "GMT+06:00", "(GMT +06:00) Almaty, Colombo, Dhaka, Novosibirsk" });
		timeZoneIDs.put("6.5", new String[] { "GMT+06:30", "(GMT +06:30) Rangoon" });
		timeZoneIDs.put("7", new String[] { "GMT+07:00", "(GMT +07:00) Bangkok, Hanoi, Jakarta" });
		timeZoneIDs.put("8", new String[] { "GMT+08:00", "(GMT +08:00) Beijing, Hong Kong, Perth, Singapore, Taipei" });
		timeZoneIDs.put("9", new String[] { "GMT+09:00", "(GMT +09:00) Osaka, Sapporo, Seoul, Tokyo, Yakutsk" });
		timeZoneIDs.put("9.5", new String[] { "GMT+09:30", "(GMT +09:30) Adelaide, Darwin" });
		timeZoneIDs.put("10", new String[] { "GMT+10:00", "(GMT +10:00) Canberra, Guam, Melbourne, Sydney, Vladivostok" });
		timeZoneIDs.put("11", new String[] { "GMT+11:00", "(GMT +11:00) Magadan, New Caledonia, Solomon Islands" });
		timeZoneIDs.put("12", new String[] { "GMT+12:00", "(GMT +12:00) Auckland, Wellington, Fiji, Marshall Island" });
	}

	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(30);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	public static boolean CheckNetworkState(Context mContext, boolean showtip) {
		synchronized (curNetWorkLock) {
			curNetWorkContext = mContext;
			boolean flag = false;
			try {
				ConnectivityManager manager = (ConnectivityManager) curNetWorkContext.getSystemService(Context.CONNECTIVITY_SERVICE);

				NetworkInfo typeMobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				State mobile = null;
				if (typeMobile != null) {
					mobile = typeMobile.getState();
				}
				NetworkInfo typeWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				State wifi = null;
				if (typeWifi != null) {
					wifi = typeWifi.getState();
				}
				// 如果3G、wifi、2G等网络状态是连接的，则退出，否则显示提示信息进入网络设置界面
				if ((mobile == State.CONNECTED) || mobile == State.CONNECTING || wifi == State.CONNECTED || wifi == State.CONNECTING)
					return true;
				else {
					if (showtip)
						Common.tip(mContext, "当前网络不可用，请检查");
					return false;
				}
			} catch (Exception e) {
				Common.tip(mContext, e.toString());
				// TODO: handle exception
			}
			return false;
		}
	}

	/**
	 * 将json 数组转换为Map 对象
	 * 
	 * @param jsonString
	 * @return
	 */

	public static Map<String, String> getMap(String jsonString) {

		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonString);
			Iterator<?> keyIter = jsonObject.keys();
			String key;
			String value;
			Map<String, String> valueMap = new HashMap<String, String>();
			while (keyIter.hasNext()) {

				key = (String) keyIter.next();
				value = (String) jsonObject.get(key);
				valueMap.put(key, value);

			}
			return valueMap;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 把json 转换为ArrayList 形式
	 * 
	 * @return
	 */
	public static List<Map<String, String>> getList(String jsonString) {

		List<Map<String, String>> list = null;
		try {
			JSONArray jsonArray = new JSONArray(jsonString);
			JSONObject jsonObject;
			list = new ArrayList<Map<String, String>>();
			for (int i = 0; i < jsonArray.length(); i++) {
				jsonObject = jsonArray.getJSONObject(i);
				list.add(getMap(jsonObject.toString()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 
	 */
	private static void showNetsetTips() {
		AlertDialog.Builder builder = new AlertDialog.Builder(curNetWorkContext);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle("没有可用网络");
		builder.setMessage("当前网络不可用，是否设置网络？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 如果没有网络连接，则进入网络设置界面
				curNetWorkContext.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		builder.create();
		builder.show();
	}

	/**
	 * 获取季度
	 */
	public static String getCurseason(int curtermbool) {

		if (0 == curtermbool) {
			return "春季";
		} else {
			return "秋季";
		}
	}

	public static String domains(String relativeurl) {
		return ServerUrl + relativeurl;

	}

	public static String getAvatarThumbs(String imageName) {
		return ServerUrl + avatar_thumbs + imageName;
	}

	public static String getAvatarOriginals(String imageName) {
		return ServerUrl + avatar_originals + imageName;
	}

	public static String getPublicImagesSmallUrl(String imageName) {
		return ServerUrl + Server_images_small + imageName;

	}

	public static String getPublicImagesMiddleUrl(String imageName) {
		return ServerUrl + Server_images_middle + imageName;

	}

	public static String getPublicImagesBigUrl(String imageName) {
		return ServerUrl + Server_images_big + imageName;

	}

	public static String getPublicAudioUrl(String audioName) {
		return ServerUrl + Server_audio + audioName;

	}

	public static String trim(String text) {
		if (text == null) {
			return "";
		}
		return text.trim();
	}

	public static String getNewUrl(int publicid, int newid) {
		return domains("data/cache/blog/blog_" + publicid + "_" + newid + ".jsp");
	}

	/**
	 * 获取字符数，一个汉字算2个字符，一个数字字母等算1一个。 该长度不是字符串实际长度。但可以和前端统一，控制显示层面的字符串长度
	 * */
	public static int getWordCount(String s) {
		int length = 0;
		for (int i = 0; i < s.length(); i++) {
			int ascii = Character.codePointAt(s, i);
			if (ascii >= 0 && ascii <= 255)
				length++;
			else
				length += 2;

		}
		return length;
	}

	/**
	 * 检查填写的密码是否符合规范
	 * */
	public static int checkPassword(String password) {
		return checkPassword(password, 6, 16);
	}

	public static int checkPassword(String password, int min, int max) {
		if (Common.empty(password)) {
			return 2;
		}
		if (!password.matches("(?is)^[a-zA-Z0-9]+$")) {
			return 1;
		}
		if (password.length() < min) {
			return 2;
		}
		if (password.length() > max) {
			return 3;
		}
		return 0;
	}

	/** 验证是不是合法的email地址格式 */
	public static boolean isEmail(String email) {
		return Common.strlen(email) > 6 && email.matches("^[\\w\\-\\.]+@[\\w\\-\\.]+(\\.\\w+)+$");
	}

	public static boolean isQqEmail(String email) {
		return Common.strlen(email) > 6 && email.matches("^[\\w\\-\\.]+@qq.com+$");
	}

	/**
	 * 返回字符串的长度，单位字节。该计算得出的字节数，和数据库是相同的。是占用数据库存储的 真实长度
	 * */
	public static int strlen(String text) {
		return strlen(text, "utf-8");
	}

	public static int strlen(String text, String charsetName) {
		if (text == null || text.length() == 0) {
			return 0;
		}
		int length = 0;
		try {
			length = text.getBytes(charsetName).length;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return length;
	}

	/** 按照规定的逻辑，对常见类型判断是否为空 */
	public static boolean empty(Object obj) {
		if (obj == null) {
			return true;
		} else if (obj instanceof String && (obj.equals("") || obj.equals("0"))) {
			return true;
		} else if (obj instanceof Number && ((Number) obj).doubleValue() == 0) {
			return true;
		} else if (obj instanceof Boolean && !((Boolean) obj)) {
			return true;
		} else if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Map && ((Map) obj).isEmpty()) {
			return true;
		} else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
			return true;
		}
		return false;
	}

	/** 使用MD5算法对字符串加密 */
	public static String md5(String arg0) {
		return MD5Util.encode(arg0);
	}

	public static String md5_3(String arg0) {
		return MD5Util.md5_3(arg0);
	}

	/**
	 * 屏蔽敏感字符
	 * 
	 * @param text
	 * @return
	 */
	public static String addSlashes(String text) {
		if (text == null || text.equals("")) {
			return "";
		}
		StringBuffer sb = new StringBuffer(text.length() * 2);
		StringCharacterIterator iterator = new StringCharacterIterator(text);
		char character = iterator.current();
		while (character != StringCharacterIterator.DONE) {
			// DONE,字符型，当迭代器已到达文本末尾或开始处时返回的常量。

			switch (character) {
			case '\'': /* 单引号 */
			case '"': /* 双引号 */
			case '\\': /* 单斜杠 */
				sb.append("\\"); /* 单斜杠 */
			default:
				sb.append(character);
				break;
			}
			character = iterator.next();
		}
		return sb.toString();
	}

	public static String formatSqlValue(String value) {
		return value.replaceAll("'", "''");
	}

	private static Toast mToast;
	private static Dialog mdialog;

	/**
	 * 提示信息
	 * 
	 * @param mContext
	 *            调用者
	 * @param msg
	 *            内容
	 * @param time
	 *            时间
	 */
	public static void tip(Context mContext, String msg) {
		tip(mContext, msg, 0);
	}

	public static void tip(Context mContext, String msg, int time) {
		if (mToast == null) {
			LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
			View layout = inflater.inflate(R.layout.mytoast, null);
			TextView message = (TextView) layout.findViewById(R.id.tv_myToastMsg);
			message.setText(msg);
			mToast = new Toast(mContext);
			if (0 == time) {
				mToast.setDuration(Toast.LENGTH_SHORT);
			} else {
				mToast.setDuration(Toast.LENGTH_LONG);
			}
			// mToast.setGravity(Gravity.CENTER, 0, 0);
			mToast.setView(layout);
		} else {
			View layout = mToast.getView();
			TextView message = (TextView) layout.findViewById(R.id.tv_myToastMsg);
			message.setText(msg);
		}
		mToast.show();
	}

	public void cancelToast() {
		if (mToast != null) {
			mToast.cancel();
		}
	}

	/**
	 * 验证用户真实姓名
	 * 
	 * @param realName
	 * @return
	 */
	public static boolean checkRealName(String realName) {
		if (!Common.empty(realName) && realName.matches("^[\u4e00-\u9fa5]+[\u00b7\\.]?[\u4e00-\u9fa5]+$"))
			return true;
		else
			return false;
	}

	/**
	 * 验证用户名
	 * 
	 * @param name
	 * @return
	 */
	public static int checkName(String name) {
		name = Common.addSlashes(Common.trim(name));
		if (!name.matches("(?is)^[0-9a-zA-Z\u4e00-\u9fa5_-|]+$")) {/*
																	 * 只能数字、汉字、字母
																	 * 、
																	 * 下划线、减号、'|'
																	 */
			return -1;
		}
		if (name.matches("^[+\\-]?\\d+(\\.\\d+)?$"))
			return -2; /* 不能全是数字 */
		int len = Common.getWordCount(name);
		if (len > 30 || len < 2)
			return -3;// 昵称长度不符合要求
		return 1;

	}

	/** 获取android版本 */
	public static int getAndroidSDKVersion() {
		int version = 0;
		try {
			version = Integer.valueOf(android.os.Build.VERSION.SDK);
		} catch (NumberFormatException e) {
			Log.e("sdk", e.toString());
		}
		return version;
	}

	public static String numToTime(int num) {
		int houre = (int) Math.floor(num / 12);
		int minute = (num - houre * 12) * 5;
		return String.format("%02d", houre) + ":" + String.format("%02d", minute);
	}

	public static void copyto(Object one, Object two) throws Exception {
		Field[] fields = two.getClass().getDeclaredFields();
		for (Field field : fields) {
			try {
				if (!Modifier.isFinal(field.getModifiers()))
					FileUtils.setValueToFiled(field, two, FileUtils.getFieldValue(field, one).toString());
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static String implode(Object data, String separator) {
		if (data == null) {
			return "";
		}
		StringBuffer out = new StringBuffer();
		if (data instanceof Object[]) {
			boolean flag = false;
			for (Object obj : (Object[]) data) {
				if (flag) {
					out.append(separator);
				} else {
					flag = true;
				}
				out.append(obj);
			}
		} else if (data instanceof Map) {
			Map<Object, ?> temp = (Map<Object, ?>) data;
			Set<Object> keys = temp.keySet();
			boolean flag = false;
			for (Object key : keys) {
				if (flag) {
					out.append(separator);
				} else {
					flag = true;
				}
				out.append(temp.get(key));
			}
		} else if (data instanceof Collection) {
			boolean flag = false;
			for (Object obj : (Collection) data) {
				if (flag) {
					out.append(separator);
				} else {
					flag = true;
				}
				out.append(obj);
			}
		} else {
			return data.toString();
		}
		return out.toString();
	}

	public static String sImplode(Object ids) {
		return "'" + implode(ids, "','") + "'";
	}

	public static int getCurYear() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		String date = format.format(new Date());
		return Integer.parseInt(date);
	}

	public static int getCurTermBool() {
		SimpleDateFormat format = new SimpleDateFormat("MM-dd");
		String[] date = format.format(new Date()).split("-");
		int month = Integer.parseInt(date[0]);
		int day = Integer.parseInt(date[1]);
		if (month >= 8 || month < 2 || (month == 2 && day < 15)) {
			return 1;// 秋季
		} else {
			return 0;// 春季
		}
	}

	public static int getCurWeekItem() {
		int week = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
		week--;
		if (week == 0) {
			week = 7;
		}
		return week;
	}

	public static String getCurWeekStr(int num) {
		String value = "";
		if (num == 0) {
			value = "未开学";
		} else {
			value = "第" + num + "周";
		}
		return value;
	}

	public static String getWeekStr(int i) {
		String num = "";
		switch (i) {
		case 1:
			num += "一";
			break;
		case 2:
			num += "二";
			break;
		case 3:
			num += "三";
			break;
		case 4:
			num += "四";
			break;
		case 5:
			num += "五";
			break;
		case 6:
			num += "六";
			break;
		case 7:
			num += "日";
			break;
		}
		return "星期" + num;

	}

	public static String sprintf(String format, double number) {
		return new DecimalFormat(format).format(number);
	}

	public static String formarImageUrl(String imageUrl) {
		return domains("attachment/" + imageUrl);

	}

	public static String formarImageThumbUrl(String imageUrl) {
		return domains("attachment/" + imageUrl + ".thumb.jpg");

	}

	public static boolean isValidTagAndAlias(String s) {
		Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
		Matcher m = p.matcher(s);
		return m.matches();
	}

	public static String getTimeOffset(String timeoffset) {
		if (Common.empty(timeoffset)) {
			timeoffset = "8";
		}
		return timeoffset;
	}

	public static String gmdate(String format, int timestamp, String timeoffset) {
		/* 注意timestamp是s为单位 */
		return getSimpleDateFormat(format, timeoffset).format(timestamp * 1000l);
	}

	public static SimpleDateFormat getSimpleDateFormat(String format, String timeoffset) {
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
		sdf.setTimeZone(TimeZone.getTimeZone(timeZoneIDs.get(timeoffset)[0]));
		return sdf;
	}

	public static String sgmdateMD(int timestamp) {
		String timeoffset = Common.getTimeOffset("8");
		String result = gmdate("MM/dd", timestamp, timeoffset);
		return result;
	}

	public static String sgmdate(int timestamp) {
		return sgmdate("yyyy-MM-dd HH:mm:ss", timestamp, true);
	}

	public static String sgmdate2(int timestamp) {
		return sgmdate("yyyy-MM-dd HH:mm:ss", timestamp, false);
	}

	public static String sgmdate3(int timestamp) {
		return sgmdate("yyyy-MM-dd", timestamp, false) + " 00:00:00";
	}

	public static String sgmdateMD2(int timestamp) {
		return sgmdate("MM/dd", timestamp, false);
	}

	public static String getChangeTime(String s) {

		try {
			return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(s).getTime() / 1000) + "";

		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";
	}

	public static String sgmdate(String dateformat, int timestamp, boolean format) {
		int curtime = (int) ((new Date()).getTime() / 1000);
		if (timestamp == 0) {
			timestamp = curtime;
		}
		String timeoffset = Common.getTimeOffset("8");
		String result = null;
		if (format) {
			int time = (Integer) curtime - timestamp;
			//
			// if (time > 31536000) {
			// result = (time / 31536000) + "年" + "前";
			// } else if (time > 86400) {
			// /* 24小时以上，用常规方式显示时间 */
			// // result = gmdate(dateformat, timestamp, timeoffset);
			// result = (time / 86400) + "天" + "前";
			// } else if (time > 3600) {
			// /* 1到24小时之间，用“x小时前”显示时间 */
			// result = (time / 3600) + "小时" + "前";
			// } else if (time > 60) {
			// /* 1分钟到1小时之间，用“x分钟前”显示 */
			// result = (time / 60) + "分" + "前";
			// } else if (time > 0) {
			// /* 1分钟内，用“x秒前”显示 */
			// result = time + "秒前";
			// } else {
			// /* 1秒内，用“现在”显示 */
			// result = "现在";
			// }

			String oldtime = Common.sgmdate2(timestamp);
			String olddate = oldtime.split(" ")[0];
			String olddatetime = oldtime.split(" ")[1].substring(0, 5);

			Calendar old = Sys.StringToDate(olddate, "yyyy-MM-dd");
			int tmp_year = old.get(Calendar.YEAR);
			int tmp_month = old.get(Calendar.MONTH) + 1;
			int tmp_day = old.get(Calendar.DAY_OF_MONTH);

			Calendar c = Calendar.getInstance();
			int new_year = c.get(Calendar.YEAR);
			int new_month = c.get(Calendar.MONTH) + 1;
			int new_day = c.get(Calendar.DAY_OF_MONTH);
			int timeday = (time / 86400);
			if (time < 60) {
				result = "刚刚";
			} else if (timeday == 0) {

				if (tmp_day == new_day) {
					result = "今天 " + olddatetime;
				} else {
					result = "昨天 " + olddatetime;
				}
			} else if (timeday == 1) {

				if (tmp_day == new_day - 1) {
					result = "昨天 " + olddatetime;
				} else {
					// result = "前天 " + olddatetime;
					result = tmp_month + "月" + tmp_day + "日 " + olddatetime;
				}
			}
			// else if (timeday == 2) {
			// if (tmp_day == new_day - 2) {
			// result = "前天 " + olddatetime;
			// } else {
			// result = tmp_month + "月" + tmp_day + "日 " + olddatetime;
			// }
			//
			// }
			else {
				if (tmp_year == new_year) {
					result = tmp_month + "月" + tmp_day + "日 " + olddatetime;
				} else {
					result = tmp_year + "年" + tmp_month + "月" + tmp_day + "日 " + olddatetime;
				}

			}

		} else {
			result = gmdate(dateformat, timestamp, timeoffset);
		}
		return result;
	}

	public static String sgmdate3(int timestamp, LinearLayout ll_bg, TextView tv_greeting_send_time) {
		int curtime = (int) ((new Date()).getTime() / 1000);
		if (timestamp == 0) {
			timestamp = curtime;
		}
		String result = null;

		int time = (Integer) curtime - timestamp;

		String ashow = "";
		if (time < 0) {
			time = -time;
			ashow = "后发送";
			if (ll_bg != null) {
				ll_bg.setBackgroundColor(Color.parseColor("#FFFFFF"));
			}
			if (tv_greeting_send_time != null) {
				tv_greeting_send_time.setTextColor(Color.parseColor("#076BAE"));
			}

			if (time > 31536000) {
				result = (time / 31536000) + "年" + ashow;
			} else if (time > 86400) {
				/* 24小时以上，用常规方式显示时间 */
				// result = gmdate(dateformat, timestamp, timeoffset);
				result = (time / 86400) + "天" + ashow;
			} else if (time > 3600) {
				/* 1到24小时之间，用“x小时前”显示时间 */
				result = (time / 3600) + "小时" + ashow;
			} else if (time > 60) {
				/* 1分钟到1小时之间，用“x分钟前”显示 */
				result = (time / 60) + "分" + ashow;
			} else if (time > 0) {
				/* 1分钟内，用“x秒前”显示 */
				result = time + "秒" + ashow;
			} else {
				/* 1秒内，用“现在”显示 */
				result = "现在";
			}

		} else {
			ashow = "前";
			if (ll_bg != null) {
				ll_bg.setBackgroundColor(Color.parseColor("#FAFAFA"));
			}
			if (tv_greeting_send_time != null) {
				tv_greeting_send_time.setTextColor(Color.parseColor("#B1B1B1"));
			}
			result = sgmdate(timestamp);
		}

		return result;
	}

	/** 判断ext是否在source中 */
	public static boolean in_array(Object source, Object ext) {
		return in_array(source, ext, false);
	}

	public static boolean in_array(Object source, Object ext, boolean strict) {
		if (source == null || ext == null) {
			return false;
		}
		if (source instanceof Collection) {
			for (Object s : (Collection) source) {
				if (s.toString().equals(ext.toString())) {
					if (strict) {
						if ((s.getClass().getName().equals(ext.getClass().getName()))) {
							return true;
						}
					} else {
						return true;
					}
				}
			}
		} else {
			for (Object s : (Object[]) source) {
				if (s.toString().equals(ext.toString())) {
					if (strict) {
						if ((s.getClass().getName().equals(ext.getClass().getName()))) {
							return true;
						}
					} else {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static JSONObject checkReturnData(String jsonString, Context cont, boolean isvalidatepassport) {
		return checkReturnData(jsonString, cont, true, isvalidatepassport);
	}

	public static JSONObject checkReturnData(String jsonString, Context cont) {
		return checkReturnData(jsonString, cont, true, true);
	}

	public static JSONObject checkReturnData(String jsonString, Context cont, boolean tip, boolean isvalidatepassport) {

		Integer code = ErrorCode.OK;
		JSONObject dataObj = null;
		if (!Common.empty(jsonString)) {
			try {
				if ("CONNECT_FAIL".equals(jsonString)) {
					if (cont != null && tip)
						Common.tip(cont, "连接服务器失败，请稍后再试");
				} else if ("CONNECT_TIMEOUT".equals(jsonString)) {
					if (cont != null && tip)
						Common.tip(cont, "网络连接超时");
				} else if ("CONNECT_EXC".equals(jsonString)) {
					if (cont != null && tip)
						Common.tip(cont, "网络连接异常");
				} else {
					dataObj = new JSONObject(jsonString);
					try {
						code = dataObj.getInt("code");
					} catch (Exception e) {
						// TODO: handle exception
					}

					if (code == 1003) {
						String msg = dataObj.getString("msg");
						if (cont != null)
							Common.tip(cont, msg);
					} else if (code == 1004 && isvalidatepassport == true) {
						if (cont != null && tip) {
							Common.tip(cont, "请重新登录");
							MyDBUser user = UserInfoManager.getUserInfoInstance(cont);
							if (user != null && user.isDataInvalid()) {
								user.setDataInvalid();
							}
							/*
							 * BaseActivity.destroyGroup("ALL"); Intent intent =
							 * new Intent(cont, LoginActivity.class);
							 * cont.startActivity(intent);
							 */
						}
					} else if (code == 1005) {
						// 弹出验证框
						if (cont != null && tip)
							Common.tip(cont, "弹出验证框");
					} else if (code == 1007) {
						if (cont != null && tip)
							Common.tip(cont, "出了点小问题");
					}
				}
			} catch (Exception e) {
				if (cont != null && tip)
					Common.tip(cont, "数据异常");
			}
		} else {
			if (cont != null && tip)
				Common.tip(cont, "服务器端异常");
		}
		return dataObj;

	}

	public static String WeekContactRollerValueChangeForSting(int index) {

		String redataStr = "";

		switch (index) {
		case 0:
			redataStr = "星期一";
			break;
		case 1:
			redataStr = "星期二";
			break;
		case 2:
			redataStr = "星期三";
			break;
		case 3:
			redataStr = "星期四";
			break;
		case 4:
			redataStr = "星期五";
			break;
		case 5:
			redataStr = "星期六";
			break;
		case 6:
			redataStr = "星期日";
			break;
		default:
			break;
		}

		return redataStr;

	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int intval(String s) {
		return intval(s, 10);
	}

	/**
	 * 将s字符串按radix进制进行解析，返回十进制的整形变量
	 * */
	public static int intval(String s, int radix) {
		if (s == null || s.length() == 0) {
			return 0;
		}
		if (radix == 0) {
			radix = 10;
		} else if (radix < Character.MIN_RADIX) {
			return 0;
		} else if (radix > Character.MAX_RADIX) {
			return 0;
		}
		int result = 0;
		int i = 0, max = s.length();
		int limit;
		int multmin;
		int digit;
		boolean negative = false;
		if (s.charAt(0) == '-') {
			negative = true;
			limit = Integer.MIN_VALUE;
			i++;
		} else {
			limit = -Integer.MAX_VALUE;
		}
		if (i < max) {
			digit = Character.digit(s.charAt(i++), radix);
			if (digit < 0) {
				return 0;
			} else {
				result = -digit;
			}
		}
		multmin = limit / radix;
		while (i < max) {
			digit = Character.digit(s.charAt(i++), radix);
			if (digit < 0) {
				break;
			}
			if (result < multmin) {
				result = limit;
				break;
			}
			result *= radix;
			if (result < limit + digit) {
				result = limit;
				break;
			}
			result -= digit;
		}
		if (negative) {
			if (i > 1) {
				return result;
			} else {
				return 0;
			}
		} else {
			return -result;
		}
	}

	public static void copy(String text, Context context) {
		ClipboardManager m = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		m.setText(text);
		Common.tip(context, "已成功复制文本");
	}

	/**
	 * 检测SDcard是否存在
	 * 
	 * @return true 存在
	 */
	public static boolean isSDcardExist() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		}

		return false;
	}

	public static String getSDFilePath() {
		return Environment.getExternalStorageDirectory().getPath() + "/com.niannian/.";
	}

	/**
	 * 获取文件夹大小
	 * 
	 * @param file
	 *            File实例
	 * @return long 单位为M
	 * @throws Exception
	 */
	public static long getFolderSize(java.io.File file) throws Exception {
		long size = 0;
		java.io.File[] fileList = file.listFiles();
		for (int i = 0; i < fileList.length; i++) {
			if (fileList[i].isDirectory()) {
				size = size + getFolderSize(fileList[i]);
			} else {
				size = size + fileList[i].length();
			}
		}
		return size / 1048576;
	}

	/**
	 * 删除指定目录下文件及目录
	 * 
	 * @param deleteThisPath
	 * @param filepath
	 * @return
	 */
	public void deleteFolderFile(String filePath, boolean deleteThisPath) throws IOException {
		if (!TextUtils.isEmpty(filePath)) {
			File file = new File(filePath);

			if (file.isDirectory()) {// 处理目录
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFolderFile(files[i].getAbsolutePath(), true);
				}
			}
			if (deleteThisPath) {
				if (!file.isDirectory()) {// 如果是文件，删除
					file.delete();
				} else {// 目录
					if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
						file.delete();
					}
				}
			}
		}
	}

	public static boolean isUrl(String urlString) {
		try {
			new URL(urlString);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	public static String showAudLen(int audlen) {
		String string = "";
		if (audlen >= 60) {
			if (audlen % 60 == 0) {
				string = (audlen / 60 + "分");
			} else {
				string = (audlen / 60 + "分" + audlen % 60 + "秒");
			}
		} else {
			string = (audlen + "秒");
		}
		return string;
	}

	public static void clearNotification(Context context) {
		NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.cancelAll();
	}

	public static void showNotification(int id, Context context, String title, String content, Class<?> clazz, String action, boolean clear) {
		NotificationManager notifimanager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.logo, content, System.currentTimeMillis());
		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		if (clear)
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
		else
			notification.flags |= Notification.FLAG_NO_CLEAR;
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		notification.defaults = Notification.DEFAULT_LIGHTS;
		notification.ledARGB = Color.BLUE;
		notification.ledOnMS = 5000;
		notification.icon = R.drawable.logo;
		Intent notificationIntent = new Intent(context.getApplicationContext(), clazz);
		notificationIntent.setAction(action);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
		notification.setLatestEventInfo(context, title, content, pendingIntent);
		notifimanager.notify(id, notification);
	}

	public static void showNotification(int id, Context context, String title, String content, int action, String ico) {
		showNotification(id, context, title, content, RegardsActivity.class, action, ico);
	}

	public static void showNotification(int id, Context context, String title, String content, Class<?> clazz, int action, String ico) {
		NotificationManager notifimanager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.logo2, content, System.currentTimeMillis());
		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.flags |= Notification.FLAG_NO_CLEAR;
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		// notification.defaults = Notification.DEFAULT_VIBRATE;

		SharedPreferences sp = context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
		if (sp.getBoolean("soundsetting", true)) {
			notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.water);
		}

		if (sp.getBoolean("isvibrate", true)) {
			long[] vibreate = new long[] { 3000 };
			notification.vibrate = vibreate;
		}
		notification.ledARGB = Color.BLUE;
		notification.ledOnMS = 5000;

		Intent notificationIntent = new Intent(context.getApplicationContext(), clazz);
		Bundle bundle = new Bundle();
		bundle.putInt("id", id);
		notificationIntent.putExtras(bundle);
		notificationIntent.setAction(action + "");
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
		// notificationIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
		notification.setLatestEventInfo(context, title, content, pendingIntent);

		try {
			Field field = Class.forName("com.android.internal.R$id").getField("icon");
			field.setAccessible(true);
			int id_icon = field.getInt(null);
			Uri uri = Uri.parse(ico);
			// new NotificationHead(id_icon,
			// notification.contentView).execute(ico);

			// Bitmap showBitmap = getNotifHead(ico);
			// if (!empty(showBitmap)) {
			// notification.contentView.setImageViewBitmap(id_icon, showBitmap);
			// }
			notification.contentView.setImageViewResource(id_icon, R.drawable.ic_launcher);
		} catch (Exception e) {
			e.printStackTrace();
		}
		notifimanager.notify(id, notification);
	}

	public static Bitmap getNotifHead(String path) {

		Bitmap showBitmap = null;

		// String imDUrl = "";
		String LimDUrl = MyApplication.FILE_PATH_TEMP + MD5Util.encode(path) + FileUtils.getImageFileExtension(path);
		File sdimage = new File(LimDUrl);
		if (!sdimage.exists()) {

		} else {
			try {
				byte[] data = FileUtils.getBytes(sdimage);
				showBitmap = BitmapDecoder.decodeSampledBitmapFromByteArray(data, 0, data.length, 100, 100);

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return showBitmap;
	}

	public static boolean isAppOnForeground(Context context) {
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = context.getPackageName();
		List<RecentTaskInfo> appTask = activityManager.getRecentTasks(Integer.MAX_VALUE, 1);

		if (appTask == null) {
			return false;
		}

		if (appTask.get(0).baseIntent.toString().contains(packageName)) {
			return true;
		}
		return false;
	}
}
